<?php

/*
* Purpose: 产生邀请码
* Author: 王照暄
*/
function gen_invitecode() {
	$today = getdate() ;
	return mt_rand(pow(10,4),pow(10,5)-1).$today['seconds'];
}

/*
* Purpose: 生成$k个数字长度的随机数
* Author: 王照暄
*/
function gen_rand_code($k) {
	return mt_rand(pow(10,$k),pow(10,$k+1)-1);
}

/*
* Purpose: 获取访问者IP地址
* Author: 王照暄
*/
function get_real_ip(){

    $headers = apache_request_headers();
    if ($headers['X-Forwarded-For']) {
        $proxies = array_reverse(split(",", $headers['X-Forwarded-For']));
        $ip = trim($proxies[0]);
        if (!$ip) {
            $ip = $_SERVER["REMOTE_ADDR"];
        }
    } elseif ($headers['Via'] && $headers['Cdn-Src-Ip']) {
        $ip = $headers['Cdn-Src-Ip'];
    } elseif ($_SERVER["REMOTE_ADDR"]) {
        $ip = $_SERVER["REMOTE_ADDR"];
    } else {
        $ip = "unknown";
    }
    return $ip;

}

/*
* Purpose: 遍历删除$dir下的所有文件以及$dir本身
* Author: 王照暄
*/
function remove_directory($dir) {
  if ($handle = opendir("$dir")) {
   while (false !== ($item = readdir($handle))) {
	 if ($item != "." && $item != "..") {
	   if (is_dir("$dir/$item")) {
		 remove_directory("$dir/$item");
	   } else {
		 unlink("$dir/$item");
	   }
	 }
   }
   closedir($handle);
   if( rmdir($dir) == TRUE) {
		return TRUE;
	} else {
		return FALSE;
	}
  }
}
function addSatelliteReplyToUserLink($content, $replytouser, $replyto_nickname) {
    if ($replytouser) {
        return preg_replace("/^@([a-z0-9_]{4,})/i", "@<a target='_new' href='/modules/satellite.php?uid=$replytouser'>$1</a> (<a href='/modules/space.php?uid=$replytouser' target='_new'>$replyto_nickname</a>)",$content);
    } else {
        return $content;
    }
}

function getContentFromUrl($url) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_TIMEOUT, 5);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    return curl_exec($curl);
}

function verifyWrite() {
    return true;

    $lastwrite = $_SESSION['G_WRITETIMESTAMP'];
    $writeval = $_SESSION['G_WRITEVAL'];
    $now = time();
    $_SESSION['G_WRITETIMESTAMP'] = $now;

    if (!$lastwrite) {
        $_SESSION['G_WRITEVAL'] = 1;
        return true;
    }
    if ($lastwrite == $now) {
        error_log("Write rejected for user ".$_SESSION['G_USERID']." - last write within the same second (URL:".$_SERVER['REQUEST_URI'].")");
        return false;
    }

    if ($now - $lastwrite < 15) {
        $writeval = $writeval * 15 / ($now - $lastwrite);
        if ($writeval > 20000) {
            error_log("Write rejected for user ".$_SESSION['G_USERID']." - write val is ".$writeval." (URL:".$_SERVER['REQUEST_URI'].")");
            return false;
        } else {
            $_SESSION['G_WRITEVAL'] = $writeval;
        }
    } else {
        $_SESSION['G_WRITEVAL'] = 1;
    }

    return true;
}

function url_signature($url)
{
    return strtr(substr(base64_encode(mhash(MHASH_MD5, $url, "meR7Qhf1QpIJxNbWN6+9t23F+")), 0, 8), '+/', '-_');
}

?>
